package com.example.testapp;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import com.google.android.gcm.server.Message;
import com.google.android.gcm.server.Result;
import com.google.android.gcm.server.Sender;

import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.text.Editable;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

public class TestActivity extends Activity implements OnClickListener{
	
	private static final String COLLAPSE_KEY = String.valueOf(Math.random());
	private static final boolean DELAY_WHITE_IDLE = true;
	private static final int TIME_TO_LIVE = 3;
	final private String senderID = "860241904445";
	final private String API_KEY = "AIzaSyCvJ-Rx3PdAHqPhPSzjLDw_LIz9uJOkKfw";
	
	public Button mSendBtn;
	public EditText mMessageEditText;
	public TextView mReceiveText;
	private Sender gcmSender;
	private Message gcmMessage;
	private Result gcmResult;
	static String registrationId;
	private String mreceiveMsg = null;
	private ListView mMessageList;
	private ArrayList<String> arMessage;
	private ArrayAdapter<String> Adapter;
	//younghoon add for location info [S]
	private LocationManager locationManager;
	LocationListener locationListener ;
	private Location location_before;
	//younghoon add for location info [E]
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	/*
    	StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
        .detectNetwork()
        .build());
        */
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);
        
        mSendBtn = (Button) findViewById(R.id.sendBtn);
        mMessageEditText = (EditText) findViewById(R.id.messageEditText);
        mReceiveText = (TextView) findViewById(R.id.resultText);
        
        mSendBtn.setOnClickListener(this);
        
      
        GCMRegistration();
        initListView();
        
        locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        criteria.setPowerRequirement(Criteria.POWER_LOW);
        String provider = locationManager.getBestProvider(criteria,true);
        Log.w("yhtest","provider = "+provider);
     // Define a listener that responds to location updates
        locationListener = new LocationListener() {
        	 
            

			public void onStatusChanged(String provider, int status, Bundle extras) {}

            public void onProviderEnabled(String provider) {}

            public void onProviderDisabled(String provider) {}

			public void onLocationChanged(Location location) {
				// TODO Auto-generated method stub
				//makeUseOfNewLocation(location);
				Log.w("yhtest","locationchanged");
				boolean isBetter = isBetterLocation(location,location_before);
				if (isBetter){
					String address = getAddressFromlocation(location.getLatitude(),location.getLongitude());
					arMessage.add(address);
					Adapter.notifyDataSetChanged();
					location_before = location;
				}
			}
          };

        // Register the listener with the Location Manager to receive location updates
          provider = LocationManager.NETWORK_PROVIDER;
          locationManager.requestLocationUpdates(provider, 0, 0, locationListener);
        
    }
    private String getAddressFromlocation(double latitude, double longitude){
    	Geocoder gck = new Geocoder(getApplicationContext(),Locale.KOREA);
    	try {
			List<Address> addresses = gck.getFromLocation(latitude, longitude, 1);
			StringBuilder sb = new StringBuilder();
	    	
			if (addresses.size()>0){
				for(Address addr:addresses){
					sb.append(addr.getMaxAddressLineIndex()).append("*\n");
					
				}
				Address address = addresses.get(0);
				sb.append(address.getCountryName()).append("\n");
				sb.append(address.getPostalCode()).append("\n");
				sb.append(address.getLocality()).append("\n");
				sb.append(address.getThoroughfare()).append("\n");
				sb.append(address.getFeatureName()).append("\n\n");
				
				//sb.append()
				String addressString = sb.toString();
				return addressString;
			}
    	} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "fail";
    	
    }
    
    private static final int TWO_MINUTES = 1000 * 60 * 2;

    /** Determines whether one Location reading is better than the current Location fix
      * @param location  The new Location that you want to evaluate
      * @param currentBestLocation  The current Location fix, to which you want to compare the new one
      */
    protected boolean isBetterLocation(Location location, Location currentBestLocation) {
        if (currentBestLocation == null) {
            // A new location is always better than no location
            return true;
        }

        // Check whether the new location fix is newer or older
        long timeDelta = location.getTime() - currentBestLocation.getTime();
        boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
        boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
        boolean isNewer = timeDelta > 0;

        // If it's been more than two minutes since the current location, use the new location
        // because the user has likely moved
        if (isSignificantlyNewer) {
            return true;
        // If the new location is more than two minutes older, it must be worse
        } else if (isSignificantlyOlder) {
            return false;
        }

        // Check whether the new location fix is more or less accurate
        int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
        boolean isLessAccurate = accuracyDelta > 0;
        boolean isMoreAccurate = accuracyDelta < 0;
        boolean isSignificantlyLessAccurate = accuracyDelta > 200;

        // Check if the old and new location are from the same provider
        boolean isFromSameProvider = isSameProvider(location.getProvider(),
                currentBestLocation.getProvider());

        // Determine location quality using a combination of timeliness and accuracy
        if (isMoreAccurate) {
            return true;
        } else if (isNewer && !isLessAccurate) {
            return true;
        } else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
            return true;
        }
        return false;
    }

    /** Checks whether two providers are the same */
    private boolean isSameProvider(String provider1, String provider2) {
        if (provider1 == null) {
          return provider2 == null;
        }
        return provider1.equals(provider2);
    }
    @Override
    public void onNewIntent(Intent intent){
    	super.onNewIntent(intent);
    	Log.w("yhtest","new intent");
    	  
          if (intent.hasExtra("msg")){
  	        Bundle bun = intent.getExtras();
  	        mreceiveMsg = bun.getString("msg");
  	        if (mreceiveMsg != null){
  	        	mReceiveText.setText(mreceiveMsg);
  	        }
  	        arMessage.add(bun.getString("msg"));
  	        Adapter.notifyDataSetChanged();
          }
          
    }
    
    private void setMessage(String text){
    	gcmSender = new Sender(API_KEY);
    	
    	gcmMessage = new Message.Builder().collapseKey(COLLAPSE_KEY)
    			.delayWhileIdle(DELAY_WHITE_IDLE)
    			.timeToLive(TIME_TO_LIVE)
    			.addData("ticker","ticker")
    			.addData("msg",text)
    			.build();
    }

	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_test, menu);
        return true;
    }
    
    public void GCMRegistration(){
    	Intent registrationIntent = new Intent("com.google.android.c2dm.intent.REGISTER");
    	// sets the app name in the intent
    	registrationIntent.putExtra("app", PendingIntent.getBroadcast(this, 0, new Intent(), 0));
    	registrationIntent.putExtra("sender", senderID);
    	startService(registrationIntent); 
    }

	public void onClick(View v) {
		// TODO Auto-generated method stub
		
		// TODO Auto-generated method stub
		switch(v.getId()){
		case R.id.sendBtn:
			//TODO 
			Log.w("yhtest","send btn");
			setMessage(mMessageEditText.getText().toString());		
			AsyncTask<Void, Void, Void> pushrequest = new  AsyncRequestPush(registrationId,gcmMessage,gcmSender).execute();
			mMessageEditText.setText("");
			break;
		
		}
	}
	private void initListView(){
		arMessage = new ArrayList<String>();
		//arMessage.add("test");
		//arMessage.add("test2");
		
		
		Adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,arMessage);
		
		mMessageList = (ListView)findViewById(R.id.message_list);
		mMessageList.setAdapter(Adapter);
		
	}
}
